package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import dm.jdbc.util.StringUtil;
import io.renren.common.constant.Constant;
import io.renren.common.exception.RenException;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.DateUtils;
import io.renren.dao.AutoDao;
import io.renren.dao.ReservationmDao;
import io.renren.dao.TradermDao;
import io.renren.dto.ReservationDto;
import io.renren.dto.ReservationmDTO;
import io.renren.dto.ReturnApiDto;
import io.renren.dto.queryDto.BillCode2Query;
import io.renren.dto.queryDto.StoreQuery;
import io.renren.entity.AutoEntity;
import io.renren.entity.RepairquotationmEntity;
import io.renren.entity.TradermEntity;
import io.renren.factory.FeginClientFactory;
import io.renren.service.FeginClientProxy;
import io.renren.service.ReservationmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.renren.entity.ReservationmEntity;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author Sen 524227263@qq.com
 * @since 1.0.0 2024-05-29
 */
@Service
public class ReservationmServiceImpl extends CrudServiceImpl<ReservationmDao, ReservationmEntity, ReservationmDTO> implements ReservationmService {

    @Autowired
    private TradermDao tradermDao;
    @Autowired
    private AutoDao autoDao;

    @Override
    public QueryWrapper<ReservationmEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<ReservationmEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public void reservation(String traderMOID, ReservationDto dto) {
        QueryWrapper<ReservationmEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("Auto_FK", dto.getAutoFk());
        wrapper.eq("Reservation_FK", dto.getReservationFk());
        wrapper.eq("ReservationContent", dto.getReservationContent());
        wrapper.eq("ReservationTime", dto.getReservationTime());
        wrapper.isNull("IsCancel");
        List<ReservationmEntity> list = baseDao.selectList(wrapper);
        if (list != null && list.size() > 0) {
            // 请勿重复预约
            throw new RenException("请勿重复预约");
        }
        BillCode2Query query = new BillCode2Query();
        query.setEncodeKind("RRE");
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getBillCode2(query);
        String billcode = result.getData().toString();

        TradermEntity tradermEntity = tradermDao.selectOne(new QueryWrapper<TradermEntity>().eq("TraderMOID", traderMOID));

        ReservationmEntity info = new ReservationmEntity();
        info.setReservationmoid(UUID.randomUUID().toString());
        info.setBillcode(billcode);
        info.setSysCreated(new Date());
        info.setBilldate(new Date());
        info.setAutoFk(dto.getAutoFk());
        info.setTradermFk(traderMOID);
        info.setReservationFk(dto.getReservationFk());
        info.setAbstracts(dto.getAbstractKey());
        // ReservationOrgName
        if (StringUtil.isNotEmpty(dto.getReservationTime())) {
            info.setReservationtime(DateUtils.parse(dto.getReservationTime(), "yyyy-MM-dd"));
        }
        info.setReservationcontent(dto.getReservationContent());
        info.setBilltype("RRE");
        info.setTimepoint(dto.getTimePoint());
        info.setEffdate(new Date());
        info.setReservationendtime(DateUtils.getEndTime(new Date()));
        info.setMobilephone(tradermEntity != null ? tradermEntity.getTel() : null);
        baseDao.insert(info);
    }

    @Override
    public Map<String, Object> myReservationList(String traderMOID) {
        QueryWrapper<ReservationmEntity> wrapper = new QueryWrapper<>();
        wrapper.select("Reservation_FK,ReservationContent,ReservationMOID,ReservationTime,Auto_FK,TraderM_FK,IsCancel,ReservationFinish,ReservationEndTime,TimePoint");
        wrapper.eq("TraderM_FK", traderMOID);
        wrapper.orderByAsc("ReservationTime,TimePoint");
        //分页
        Map<String, Object> params = new HashMap<>();
        params.put("limit", "9999");

        IPage<ReservationmEntity> page = getPage(params, Constant.CREATE_DATE, false);

        IPage<ReservationmEntity> pageData = baseDao.selectPage(page, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", pageData.getTotal());
        map.put("per_page", pageData.getPages());
        map.put("current_page", pageData.getCurrent());
        map.put("last_page", page.maxLimit());
        List<Map<String, Object>> listRes = new ArrayList<>();
        for (ReservationmEntity item : pageData.getRecords()) {
            Map<String, Object> mapItem = new HashMap<>();
            mapItem.put("ReservationMOID", item.getReservationmoid());
            mapItem.put("ReservationTime", item.getReservationtime());
            mapItem.put("Auto_FK", item.getAutoFk());
            mapItem.put("TraderM_FK", item.getTradermFk());
            mapItem.put("IsCancel", item.getIscancel());
            mapItem.put("ReservationFinish", item.getReservationfinish());
            mapItem.put("ReservationEndTime", item.getReservationendtime());
            mapItem.put("TimePoint", item.getTimepoint());

            AutoEntity autoEntity = autoDao.selectOne(new QueryWrapper<AutoEntity>().eq("AutoOID", item.getAutoFk()));
            if (autoEntity != null) {
                mapItem.put("AutoNo", autoEntity.getAutono());
            }

            List<String> statusArr = autoDao.getStatusListByReservationMOID(item.getReservationmoid());
            if (statusArr != null && statusArr.size() > 0) {
                mapItem.put("statusName", statusArr.get(0));
            }
            mapItem.put("ReservationTime", DateUtils.format(item.getReservationtime(), "yyyy-MM-dd") + " " + item.getTimepoint());
            // todo 新增返回 ： 预约门店和服务类型
            Map<String, Object> codeMap = autoDao.getReservationContent(item.getReservationcontent());
            mapItem.put("reservationContent", codeMap != null ? codeMap.get("CodeName") : "");
            Map<String, Object> codeMap2 = autoDao.getOrganize(item.getReservationFk());
            mapItem.put("reservationName", codeMap2 != null ? codeMap2.get("OrgName") : "");
            listRes.add(mapItem);
        }
        map.put("data", listRes);

        return map;
    }

    @Override
    public void cancelReservation(String traderMOID, String reservationMoId, String cancelReason) {
        ReservationmEntity reservationmEntity = new ReservationmEntity();
        reservationmEntity.setIscancel("1");
        reservationmEntity.setCancelreason(cancelReason);
        reservationmEntity.setCanceltime(new Date());

        QueryWrapper<ReservationmEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("ReservationMOID", reservationMoId);
        baseDao.update(reservationmEntity, wrapper);
    }
}